package com.md.drcs.dicom.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.md.common.dto.page.Pagination;
import com.md.common.dto.page.ResponseQuery;
import com.md.common.exception.BaseBizException;
import com.md.common.exception.BaseErrorCode;
import com.md.drcs.dicom.dao.*;
import com.md.drcs.dicom.dto.PatientStudyGenResp;
import com.md.drcs.dicom.dto.StudyDetailDTO;
import com.md.drcs.dicom.dto.UserPatientStudyDTO;
import com.md.drcs.dicom.entity.PatientEntity;
import com.md.drcs.dicom.entity.ReportEntity;
import com.md.drcs.dicom.entity.StudyEntity;
import com.md.drcs.dicom.service.StudyService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("studyService")
public class StudyServiceImpl implements StudyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudyService.class);

//    @Value("${study.image.server}")
    private String imageServer;
//    @Value("${study.image.path}")
    private String studyImagePath;
//    @Value("${study.image-view.server}")
    private String studyImageViewServer;
//    @Value("${study.report-pdf.server}")
    private String reportPDFServer;
//    @Value("${study.report.path}")
    private String studyReportPath;
    @Autowired
    private StudyDao studyDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private ReportDao reportDao;
    @Autowired
    private SeriesDao seriesDao;
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private StudyCollectDao studyCollectDao;

    @Override
    public StudyDetailDTO get(Long id)  {
        return  null;
    }


    @Override
    public StudyEntity getBasic(Long id) {
        StudyEntity study = studyDao.selectByPrimaryKey(id);
        if (study == null)
            throw new BaseBizException(BaseErrorCode.INVALID_DATA, "暂未查询到您的检查信息，请您稍后再试");
        return study;
    }

    @Override
    public StudyEntity getBasicByHospStudyId(String hospStudyId,String hospId) {
        StudyEntity study = studyDao.getBasicByHospStudyId(hospStudyId,hospId);
        if (study == null)
            throw new BaseBizException(BaseErrorCode.INVALID_DATA, "暂未查询到您的检查信息，请您稍后再试");
        return study;
    }

    @Override
    public boolean dealConsulReport(Long id,String sRep,String sCon){
        ReportEntity reportOrigin = reportDao.findByStudyId(id);
        if (null == reportOrigin){
            return false;
        }

        reportOrigin.setNType(1);
        reportOrigin.setSRep(sRep);
        reportOrigin.setSCon(sCon);

        //如果不存在会诊报告的记录
        ReportEntity reportConsul = reportDao.findByStudyIdForConsul(id);
        if (null == reportConsul){
            int num = reportDao.insertUseGeneratedKeys(reportOrigin);
            return 1 == num;
        }

        //更新会诊报告也以原始报告为基准,数据全以原始报告的为准,主键是会诊报告的主键
        reportOrigin.setNReportId(reportConsul.getNReportId());
        int num = reportDao.updateByPrimaryKey(reportOrigin);
        return 1 == num;
    }

    @Override
    public ResponseQuery<UserPatientStudyDTO> findByPatient(Pagination pagination, Long patientId, String hospId) {
        Page<Object> page = PageHelper.offsetPage(pagination.getStart(), pagination.getPageSize());
        PatientEntity patient = patientDao.selectByPrimaryKey(patientId);
        List<PatientEntity> patients = patientDao.findByPatIdInPacs(patient.getSPatIdInPacs(), hospId);
        List<UserPatientStudyDTO> userPatientStudys = new ArrayList<>();
        for (PatientEntity pat : patients) {
            userPatientStudys.addAll(studyDao.findByPatientId(pat.getNPatId()));
        }
        List<String> hospNos = userPatientStudys.stream().map(UserPatientStudyDTO::getsHosNo).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(hospNos)) {
            List<Long> excludeStudyIds = userPatientStudys.stream().map(UserPatientStudyDTO::getnStuId).collect(Collectors.toList());
            List<UserPatientStudyDTO> sameHosNoStudies = studyDao.findByHosNos(hospNos, patient.getSName(), excludeStudyIds);
            userPatientStudys.addAll(sameHosNoStudies);
        }
        for (UserPatientStudyDTO study : userPatientStudys) {

            ReportEntity report = reportDao.findByStudyId(study.getnStuId());
            if (report == null)
                continue;
            if (!StringUtils.equals(study.getsStuStatus(), "已审核") && !StringUtils.equals(study.getsStuStatus(), "已打印"))
                continue;
            if (report.getAudDate() == null) {
                study.setStatus(1);
            }
            if(StringUtils.isBlank(report.getSReportPath())) {
                LOGGER.debug("pdf file not exists (path is null)");
                continue;
            }
            String path = String.format("%s%s/%s/%s", study.getDiskCode(), studyReportPath, study.getsHospId(), report.getSReportPath());
            if (!new File(path).exists()) {
                LOGGER.debug("pdf file not exists, {}", path);
                continue;
            }
            // 由nginx代理/report-view/disk-{code}/处理查看PDF请求
            String pdf = String.format("%s/report-view/disk-%s/%s/%s",
                    reportPDFServer, StringUtils.lowerCase(study.getDiskCode()), study.getsHospId(),
                    report.getSReportPath().replace("\\\\", "\\").replace("\\", "/"));
            study.setReportPDF(pdf);
        }

        return new ResponseQuery<>(userPatientStudys, page.getTotal(), page.getPages());
    }

    @Override
    public boolean existsDicomFile(Long studyId) {

        return false;
    }

    @Override
    public StudyEntity getBasicByStuIdInPacs(String stuIdInPacs, String hospId) {
        StudyEntity study = studyDao.getBasicByStuIdInPacs(stuIdInPacs, hospId);
        if (study == null)
            throw new BaseBizException(BaseErrorCode.INVALID_DATA, "暂未查询到您的信息，请您稍后再试");
        return study;
    }

    @Override
    public StudyEntity getByAccessNumber(String accessNumber, String hospId) {
        StudyEntity study = studyDao.getByAccessNumber(accessNumber, hospId);
        if (study == null)
            throw new BaseBizException(BaseErrorCode.INVALID_DATA, "暂未查询到您的信息，请您稍后再试");
        return study;
    }

    @Override
    public StudyEntity getByPatientHospNo(String hospNo, String hospid) {
        StudyEntity study = studyDao.getByHospNo(hospNo, hospid);
        if (study == null)
            throw new BaseBizException(BaseErrorCode.INVALID_DATA, "暂未查询到您的信息，请您稍后再试");
        return study;
    }

    @Override
    public List<PatientStudyGenResp> findByStudyDate(LocalDateTime begin, LocalDateTime end) {
        return studyCollectDao.findByStudyDate(begin, end);
    }

    @Override
    public LocalDateTime getPrintTime(String stuidInPacs) {
        return studyDao.getPrintTime(stuidInPacs);
    }
}
